<?php
namespace app\distribution\controller\sys_admin;
use app\AdminController;

use app\distribution\model\LadderLogModel;
use app\member\model\UsersModel;
use app\shop\model\OrderModel;
use think\Db;

//*------------------------------------------------------ */
//-- 佣金明细
/*------------------------------------------------------ */
class LadderLog extends AdminController{
    //*------------------------------------------------------ */
    //-- 初始化
    /*------------------------------------------------------ */
    public function initialize(){
        parent::initialize();
        $this->Model = new LadderLogModel();
    }

    //*------------------------------------------------------ */
    //-- 首页
    /*------------------------------------------------------ */
    public function index(){

        $this->assign("start_date", date('Y/m/01',strtotime("-1 months")));
        $this->assign("end_date",date('Y/m/d'));
        $this->getList(true);
        return $this->fetch('index');
    }
    /*------------------------------------------------------ */
    //-- 获取列表
    //-- $runData boolean 是否返回模板
    /*------------------------------------------------------ */
    public function getList($runData = false,$is_cancel = false){
        $orderlang = lang('order');
        $this->assign("divdend_satus", $orderlang['ds']);
        $search['status'] = input('status','-1','intval');
        $search['keyword'] = input('keyword','','trim');
        $reportrange = input('reportrange');
        $where = [];
//		if ($search['status'] >= 0 ){
//			$where[] = ['status','=',$search['status']];
//		}
//		if (empty($search['keyword']) == false){
//			$where[] = ['sn|user_id','=',$search['keyword']*1];
//		}
//		if (empty($reportrange) == false){
//			$dtime = explode('-',$reportrange);
//			$where[] = ['addtime','between',[strtotime($dtime[0]),strtotime($dtime[1])+86399]];
//		}else{
//			$where[] = ['addtime','between',[strtotime("-1 months"),time()]];
//		}
        $where[] = ['role_id','=',14];
        $model = new UsersModel();
        $data = $this->getPageList($model, $where);
        $setting = Db::name('lc_config')->where('id',1)->find();
        $level = [];
        $goods_ids = [];
        if($setting['team']){
            $setting['team'] = json_decode($setting['team'],true);
            $goods_ids = array_column($setting['team']['goods'],'goods_id');
        }
        if($setting['star']){
            $setting['star'] = json_decode($setting['star'],true);
            foreach ($setting['star']['config'] as $v){
                $level[$v['level']] = $v['name'];
            }
        }
        foreach ($data['list'] as &$value){
            $child = $this->getTeamLevelIds($value['user_id'],[]);
            $child[] = $value['user_id'];
            $order_num = Db::name('shop_order_info')->alias('o')->join('shop_order_goods og','og.order_id = o.order_id')
                ->where('og.goods_id','in',$goods_ids)->whereTime('pay_time', 'month')->where('o.user_id','in',$child)->count();
            $xj_total_award = Db::name('users_account_log')->where(['user_id' => $value['user_id'],'change_type' => 30])->sum('balance_money');
            $xj_award = Db::name('users_account_log')->where(['user_id' => $value['user_id'],'change_type' => 30])
                ->whereTime('change_time', 'month')->sum('total_dividend');
            $team_total_award = Db::name('users_account_log')->where(['user_id' => $value['user_id'],'change_type' => 42])->sum('balance_money');
            $value['lc_xj'] =  $level[$value['lc_level']];
            $value['team_order'] = $order_num;
            $value['xj_award'] = $xj_award;
            $value['xj_total_award'] = $xj_total_award;
            $value['team_award'] = $this->getLcTeamAward($value['user_id']);
            $value['team_total_award'] = $team_total_award + $value['team_award'];
        }
//exit;
//        $data = Db::name('users')->where([])->paginate(10);
        $this->assign("data", $data);
        $this->assign("search", $search);
        if ($runData == false){
            $data['content'] = $this->fetch('list')->getContent();
            unset($data['list']);
            return $this->success('','',$data);
        }
        return true;
    }

    public function order(){

        $this->assign("start_date", date('Y/m/01',strtotime("-1 months")));
        $this->assign("end_date",date('Y/m/d'));
        $this->getOrderList(true);
        return $this->fetch('order');
    }

    public function getOrderList($runData = false,$is_cancel = false){
        $user_id = input('user_id');
        $orderlang = lang('order');
        $this->assign("divdend_satus", $orderlang['ds']);
        $search['status'] = input('status','-1','intval');
        $search['keyword'] = input('keyword','','trim');
        $reportrange = input('reportrange');
        $where = [];
        $child = $this->getTeamLevelIds($user_id,[]);
        $child[] = $user_id;
        $where[] = ['user_id','in',$child];
        $where[] = ['pay_status','=',1];
        $where[] = ['pay_time','>=',strtotime(date('Y-m-01'))];
        $where[] = ['pay_time','<=',strtotime(date('Y-m-t 23:59:59'))];
        $model = new OrderModel();
        $data = $this->getPageList($model, $where);

//        foreach ($data['list'] as &$value){
//
//        }

//        $data = Db::name('users')->where([])->paginate(10);
        $this->assign("data", $data);
        $this->assign("search", $search);
        if ($runData == false){
            $data['content'] = $this->fetch('order_list')->getContent();
            unset($data['list']);
            return $this->success('','',$data);
        }
        return true;
    }
    /**
     * @param $user_id
     * @param $return_arr
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTeamLevelIds($user_id,$return_arr){
        $child_list = Db::name('users')->where(['pid' => $user_id])->select();
        if($child_list){
            foreach ($child_list as $val){
                $return_arr[] = $val['user_id'];
                $return_arr =  self::getTeamLevelIds($val['user_id'],$return_arr);
            }
        }
        return $return_arr;
    }

    /**
     * @param $user_id
     * @param $goods_ids
     * @return float|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getLcTeamAward($user_id){
        $setting = Db::name('lc_config')->where('id',1)->find();
        $goods_ids = [];
        if($setting['team']){
            $setting['team'] = json_decode($setting['team'],true);
            $goods_ids = array_column($setting['team']['goods'],'goods_id');
        }
        if(!$goods_ids){
            return 0;
        }
        $child = $this->getTeamLevelIds($user_id,[]);
        $child[] = $user_id;
        $order_num = Db::name('shop_order_info')->alias('o')->join('shop_order_goods og','og.order_id = o.order_id')
            ->where('og.goods_id','in',$goods_ids)->whereTime('pay_time', 'month')
            ->where('o.user_id','in',$child)->count();
        //直推列表
        $child_list = Db::name('users')->where(['pid' => $user_id])->select();

        $amount = $this->calculateAward($order_num);

        $total_amount = $amount;
        foreach ($child_list as $value){
            //查找每条线的联创
            $lc_uid = $this->getTeamLevel($value['user_id']);
            if($lc_uid){
                $childs = $this->getTeamLevelIds($lc_uid,[]);
                $childs[] = $lc_uid;
                $order_num = Db::name('shop_order_info')->alias('o')->join('shop_order_goods og','og.order_id = o.order_id')
                    ->whereTime('pay_time', 'month')->where('og.goods_id','in',$goods_ids)->where('o.user_id','in',$childs)->count();
                $sub_order_num = $order_num;
                $sub_amount = $this->calculateAward($sub_order_num);
                $total_amount = $total_amount - $sub_amount;
            }
        }
        return $total_amount;
    }

    /**
     * @param $num
     * @return float|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function calculateAward($num)
    {
        $setting = Db::name('lc_config')->where('id',1)->find();
        $config = [];
        $award = 0;
        if($setting['team']){
            $setting['team'] = json_decode($setting['team'],true);
            $config = $setting['team']['config'];
            $config = array_reverse($config);
            foreach ($config as $value){
                if($value['min_order_num'] <= $num && $num <= $value['max_order_num']){
                    $award = $value['award_amount'];
                    break;
                }
            }
        }
        return $award * $num;
    }

    /**
     * @param $user_id
     * @return mixed|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTeamLevel($user_id){
        $user = Db::name('users')->where(['user_id' => $user_id])->select();
        if($user['role_id'] == 14){
            return $user_id;
        }else{
            $child_list = Db::name('users')->where(['pid' => $user_id])->select();
            if($child_list){
                foreach ($child_list as $val){
                    if($val['role_id'] == 14){
                        return $val['user_id'];
                    }else{
                        return self::getTeamLevel($val['user_id']);
                    }
                }
            }
        }
    }
}
